package com.ojoin.trade.supplyloan_core.web.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.ojoin.trade.bpm.web.service.BpmTaskService;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.*;
import com.ojoin.trade.supplyloan_core.web.domain.*;
import com.ojoin.trade.supplyloan_core.web.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ojoin.trade.bpm.web.support.ProcessMessageVO;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.interceptor.AvoidDuplicateSubmission;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Pair;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.BranchBaseService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.support.ActiveMQSender;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-11-16
 * Time: 下午3:16
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/credit")
public class SlCreditLogController  extends SimpleBaseController {

    private Logger log = LoggerFactory.getLogger(SlCreditLogController.class);

    @Autowired
    private TbSlLoanService loanService;

    @Autowired
    private TbSlPlatformUserService platformUserService;

    @Autowired
    private TbSlLoanInfoService tbSlLoanInfoService;

    @Autowired
    private TbSlLoanCreditService creditService;

    @Autowired
    private TbSlLoanRefundService refundService;

    @Autowired
    private AccountBaseService accountBaseService;

    @Autowired
    private TbSlLoanStatTotalService slLoanStatTotalService;

    @Autowired
    private TbSlPlatformInfoService tbSlPlatformInfoService;

    @Autowired
    private TbSLLoanInfoLogService tbSLLoanInfoLogService;
    
    @Autowired
    private TbSlBankaccService tbBankaccService;

    @Autowired
    private BranchBaseService branchBaseService;
    
    @Autowired
    private IRSAService rsaSrv;

	@Autowired
	private TbUploadFileService uploadService;

    @Autowired
    private TbSlLoanApplicationService tbSlLoanApplicationService;

    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;

    @Autowired
    private BpmTaskService bpmTaskService;
    
    @Autowired  
    @Qualifier("creditLogQueueDestination")  
    private Destination destination;  
    
    /**
     * 查询当前用户的供应链贷款的可提限额
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querycanloanamount", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result queryCanLoanAmount(HttpServletRequest request) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            String canloanamount = loanService.getMaxLoanAmount(joinid,ISLConstDef.MERCHANT_TYPE);
            return new Result(Result.Status.OK, canloanamount);
        } catch (Exception e) {
            log.error("查询用户的可提限额有误", e);
            if(e instanceof BusinessException){
            return new Result(Result.Status.ERROR, e.getMessage());
            }else{
                return new Result(Status.ERROR,"系统异常");
            }
        }
    }

    /**
     *查询商户的保理合同和营业执照的到期日
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryExpireDate", method = RequestMethod.GET)
    public Result queryApplicationVo(HttpServletRequest request){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
           try{
               TbSlLoanApplication vo=tbSlLoanApplicationService.queryTbSlApplicationByJoinId(joinid);
               if(null==vo){
                   return new Result(Status.OK, Lists.newArrayList());
               }
               String yyzzExpireDate=vo.getYyzzExpireDate();
               String blhtExpireDate=vo.getCreditEndDate();
               List<ContractExpireVo> list=new ArrayList<>();
               ContractExpireVo blht=new ContractExpireVo();
               blht.setContractType("blht");
               blht.setExpiredDate(blhtExpireDate);
               blht.setWindow(30);
               blht.setExpiredDay((int)TimeUtils.getDateSpaceOfDay(TimeUtils.getCurDate(), blht.getExpiredDate())+1);
               boolean blhtExpired=(blht.getExpiredDay()-blht.getWindow())<=0;
               blht.setExpired(blhtExpired);
               list.add(blht);
               
               ContractExpireVo yyzz=new ContractExpireVo();
               yyzz.setContractType("yyzz");
               yyzz.setExpiredDate(yyzzExpireDate);
               yyzz.setWindow(90);
               yyzz.setExpiredDay((int)TimeUtils.getDateSpaceOfDay(TimeUtils.getCurDate(), yyzz.getExpiredDate())+1);
               boolean yyzzExpired=(yyzz.getExpiredDay()-yyzz.getWindow())<=0;
               yyzz.setExpired(yyzzExpired);
               list.add(yyzz);
               return new Result(Status.OK,list);
           }catch (Exception  e){
               LogUtils.error(log,e,"查询商户的营业执照合同到期出错");
               return new Result(Status.ERROR,"系统出错，请联系九盈科技");
           }
    }
    /**
     * 查询用户的电商平台
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPlatform", method = RequestMethod.GET)
    public Result queryPlatform(HttpServletRequest request) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            List<TbSlPlatformUser> list = platformUserService.selectPlatformUserListByJoinID(joinid);
            if (!CommonUtils.isEmpty(list)) {
                for (TbSlPlatformUser user : list) {
                    String paltformname = user.getPlatformName();
                    TbSlPlatformInfo info = tbSlPlatformInfoService.queryByName(paltformname);
                    user.setPlatformCnname(info.getPlatformCnname());
                }
            }
            return new Result(Result.Status.OK, list);
        } catch (Exception e) {
            log.error("查询用户的平台用户", e);
            return new Result(Result.Status.ERROR, "查询用户的平台信息出错");

        }

    }

    /**
     * 账号相同不能添加
     * 业务申请完成后新增平台
     */
    @ResponseBody
    @RequestMapping(value = "/addMuti",method = RequestMethod.POST)
    public Result addMuti(HttpServletRequest request,@RequestBody List<TbSlPlatformUser> entitys) {
        SessionUser suser=CommonUtils.getSessionUser(request);
        Integer joinId = suser.getId();
        if(CollectionUtils.isNotEmpty(entitys)){
            for(TbSlPlatformUser puser:entitys){
            	
            	TbSlPlatformUser paramUser=new TbSlPlatformUser();
            	paramUser.buildDefaultEntity();
            	paramUser.setIdOfTbMerchantUser(puser.getIdOfTbMerchantUser());
            	paramUser.setPlatformName(puser.getPlatformName());
            	paramUser.setUsername(puser.getUsername());
            	paramUser.setEnableFlag(null);
            	List<TbSlPlatformUser> queryList = platformUserService.queryList(paramUser);
				if(null!=queryList&&queryList.size()>0){
            		return new Result(Status.ERROR, String.format("平台用户账号:%s已经存在",puser.getUsername()));
            	}
				puser.buildDefaultEntity();
                puser.setIdOfTbMerchantUser(joinId);
                puser.encPassword();
                puser.setEnableFlag(ISLConstDef.PLATFORM_STATUS_INITED);
            }
            platformUserService.insertInBatch(entitys);
        }
        return new Result(Status.OK, "保存成功");
    }

    @ResponseBody
    @RequestMapping(value = "/updateMuti",method = RequestMethod.POST)
    public Result updateMuti(HttpServletRequest request,@RequestBody List<TbSlPlatformUser> entitys) {
        SessionUser suser=CommonUtils.getSessionUser(request);
        Integer joinId = suser.getId();
        if(CollectionUtils.isNotEmpty(entitys)){
            for(TbSlPlatformUser puser:entitys){
                puser.setIdOfTbMerchantUser(joinId);
                puser.encPassword();
                puser.setEnableFlag(ISLConstDef.PLATFORM_STATUS_ENABLED);
            }
            platformUserService.updateInBatch(entitys);
        }
        return new Result(Status.OK, "更新成功");
    }
    
    @RequestMapping(value = "/removePlatform", method = RequestMethod.POST)
    public Result removePlatform(HttpServletRequest request,Integer id) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        platformUserService.deleteByJoinAndId(joinid,id);
        return new Result(Result.Status.OK, "删除完成");
    }

    /**
     * 查询用户的总贷款记录
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryloaninfo", method = RequestMethod.GET)
    public Result queryLoanInfo(HttpServletRequest request) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            TbSlLoanInfo info = tbSlLoanInfoService.queryLoanInfoByJoinid(joinid);
            return new Result(Result.Status.OK, info);
        } catch (Exception e) {
            log.error("查询用户的贷款情况出错", e);
            return new Result(Result.Status.ERROR, "查询用户的贷款情况出错");
        }
    }

    /**
     * 查询用户的未还款记录
     *
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querynotpayback", method = RequestMethod.GET)
    public Result queryNotPayback(HttpServletRequest request, Pageable page) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            TbSlNotPayBackCreditForFront vo = creditService.queryNotPayback(joinid,page);
            return new Result(Result.Status.OK, vo);
        } catch (Exception e) {
            log.error("查询用户未还贷款数据有误", e);
            return new Result(Result.Status.ERROR, "查询用户未还贷款数据有误");
        }
    }

    /**
     * 查询用户的已还款记录
     *
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querypayback", method = RequestMethod.GET)
    public Result queryPayback(HttpServletRequest request, Pageable page) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            List<TbSlLoanCreditLog> logList = creditService.queryPaybackByJoinid(joinid, page);
            return new Result(Result.Status.OK, logList);
        } catch (Exception e) {
            log.error("查询商户的已还款的贷款信息出错", e);
            return new Result(Result.Status.ERROR, "查询商户的已还款的贷款信息出错");
        }

    }



    @ResponseBody
    @RequestMapping(value = "/applyloan", method = RequestMethod.POST)
    public Result applyloan(HttpServletRequest request,@RequestBody SlApplyLoanParam param) {
        if (CommonUtils.isEmpty(param.getMobileVerifyCode())) {
            return new Result(Result.Status.ERROR, "验证码不能为空");
        }
        if (CommonUtils.isEmpty(param.getAmount())) {
            return new Result(Result.Status.ERROR, "提款金额不能为空");
        }
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        String mthno = TradeUtils.getMhtNo(request);
        String cachecode = SMSHelper.getModifyAccountInfoValidateCode(mthno);
        if (!param.getMobileVerifyCode().equals(cachecode)) {
            return new Result(Result.Status.ERROR, "验证码错误");
        }
        double amountdouble = Double.parseDouble(param.getAmount());
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        try {
            Integer idofbankacc=null;
            if(!IConstDef.ACCTYPE_BASE.equals(param.getIdOfBankacc())){
                idofbankacc=Integer.parseInt(param.getIdOfBankacc());
            }
             List<TbSlLoanCreditLog> list= loanService.updateForReLoan(amountlong, joinid, mthno, param.getFrontvo(), idofbankacc);
            SMSHelper.clearModifyAccountInfoValidateCode(mthno);
            return new Result(Result.Status.OK,list);
        } catch (Exception e) {
            log.error("提款失败", e);
            if (e instanceof BusinessException) {
                return new Result(Result.Status.ERROR, e.getMessage());
            }
            return new Result(Result.Status.ERROR, "提款失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/downLoanDoc", method = RequestMethod.GET)
    public void downloadSlLoanCommitFile(
            HttpServletRequest request,
            HttpServletResponse response, int id) throws IOException {
        TbSlLoanCreditLog creditlog = creditService.queryCreditLogById(id);
        TbUploadFile uploadFileVO = uploadService.queryById(CommonUtils.getInt(creditlog.getMaterialDownload()));
		String filename = IConstDef.DOWNLOAD_LOANAPPLY + "." + FilenameUtils.getExtension(uploadFileVO.getDownloadPath());
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir()+File.separator+uploadFileVO.getDownloadPath(), filename);
		LogUtils.info(log, "下载%s",IConstDef.DOWNLOAD_LOANAPPLY);
    }

    @ResponseBody
    @RequestMapping(value = "/queryrepay", method = RequestMethod.GET)
    public Result queryRepay(HttpServletRequest request, Pageable page) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            List<TbSlRepayCreditVo> list = refundService.queryRepayCreditByJoinid(joinid, page);
            return new Result(Result.Status.OK, list);
        } catch (BusinessException e) {
            LogUtils.error(log, e, "查询用户的已还款记录出错");
            return new Result(Result.Status.ERROR, "查询用户的已还款记录出错");
        }


    }

    /**
     * 上传欠款合同
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadDebtAgreementFile", method = RequestMethod.POST)
    public void uploadDebtAgreementFile(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "debtAgreementFile", required = false) MultipartFile file) throws IOException{
            Result res=CommonUtils.getPathUploadedFile(request, response, file, ISLConstDef.slLoanDebtAgreementFileDir);
            CommonUtils.sendJOSNResponse(response,res);
    }
    @AvoidDuplicateSubmission(needRemoveToken = true)
    @ResponseBody
    @RequestMapping(value = "/uploadloanapply", method = RequestMethod.POST)
    public Result uploadLoanApply(HttpServletRequest request, @RequestBody  SlWithdrawParam param) {
        List<Integer> idlist=new ArrayList<>();
        Map<String,Object> vars=new HashMap<>();
        Integer processid;
        StringBuffer title=new StringBuffer();
        try {
            creditService.updateBatchForFile(param.getList(), param.getFilepath());

            for(TbSlLoanCreditLog logvo:param.getList()){
              idlist.add(logvo.getId());
            }
            
           vars=tbSlLoanApplicationService.initProcessRole(idlist.get(0));
           List<TbSlLoanCreditLog> list=creditService.queryCodeById(idlist);
           processid=param.getList().get(0).getProcessInfoId();

           for(TbSlLoanCreditLog log:list){
                title.append(log.getCode()).append("   ");
           }
        } catch (Exception e) {
            LogUtils.error(log, e, "贷款的申请书失败");
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Result.Status.ERROR, "贷款申请书失败");
        }
                String loginName = CommonUtils.getPrincipal().getLoginName();
        	   ProcessMessageVO vo = new ProcessMessageVO();
        	   vo.setProcDefKey("SLCredit");
        	   vo.setBusinessTable("tb_sl_process_info");
        	   vo.setBusinessId(String.valueOf(processid));
        	   vo.setLoginName(loginName);
        	   vo.setTitle(title.toString());
        	   vo.setVars(vars);
//              bpmTaskService.startProcess(vo.getProcDefKey(),vo.getBusinessTable(), vo.getBusinessId(),vo.getTitle(),vo.getLoginName(), vo.getVars());
        	   ActiveMQSender.getInstance().asyncSend(destination, vo);
            return new Result(Result.Status.OK, "贷款申请书成功");


    }
    @ResponseBody
    @RequestMapping(value = "/uploadApplyForDetail",method = RequestMethod.POST)
    public Result uploadApplyForDetail(HttpServletRequest request,String processid,String ts,String filepath){
        Map<String,Object> vars=new HashMap<>();
        StringBuffer title=new StringBuffer();
      try{
          loanService.updateForUploadFile(Integer.parseInt(processid),ts,filepath);
          List<TbSlStatusCreditLogVo> listvo=creditService.queryCreditByProcessid(Integer.parseInt(processid));

          vars=tbSlLoanApplicationService.initProcessRole(listvo.get(0).getId());
          for(TbSlStatusCreditLogVo log:listvo){
              title.append(log.getCode());
          }
      } catch (Exception e) {
          LogUtils.error(log, e, "贷款的申请书失败");
          if(e instanceof BusinessException){
              return new Result(Status.ERROR,e.getMessage());
          }
          return new Result(Result.Status.ERROR, "贷款申请书失败");
      }
           String loginName = CommonUtils.getPrincipal().getLoginName();
            ProcessMessageVO vo = new ProcessMessageVO();
            vo.setProcDefKey("SLCredit");
            vo.setBusinessTable("tb_sl_process_info");
            vo.setBusinessId(String.valueOf(processid));
            vo.setLoginName(loginName);
            vo.setTitle(title.toString());
            vo.setVars(vars);
        bpmTaskService.startProcess(vo.getProcDefKey(),vo.getBusinessTable(), vo.getBusinessId(),vo.getTitle(),vo.getLoginName(), vo.getVars());
          return new Result(Status.OK,"提交贷款申请成功");
    }

    @ResponseBody
    @RequestMapping(value = "/repay", method = RequestMethod.POST)
    public Result repay(HttpServletRequest request, @RequestBody SlAutoRepayParam param) {
        if (param==null ||param.getListvo()==null) {
            return new Result(Result.Status.ERROR, "未选择任何要还款的贷款记录");
        }
        if(CommonUtils.isEmpty(param.getPwd())){
            return new Result(Status.ERROR,"支付密码不能为空");
        }
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try {
            String mhtno = TradeUtils.getMhtNo(request);
            String accamount = accountBaseService.queryBalance(mhtno, IConstDef.ACCTYPE_BASE);
            if (StringUtils.isEmpty(accamount)) {
                return new Result(Result.Status.ERROR, "查询基本户余额为0，请先充值再还款");
            }
             String  pwd=rsaSrv.decryptStringByJs(param.getPwd());
            loanService.updateForRepayLoan(joinid,param.getListvo(),param.getLoanInfoVo() ,pwd,accamount, IConstDef.ACCTYPE_BASE);
            return new Result(Result.Status.OK, "还款成功");
        } catch (Exception e) {
            LogUtils.error(log, e, "还款失败");
            if(e instanceof IPayNowException){
                return new Result(Status.WARNING,"处理中");
            }
            if (e instanceof BusinessException) {
                return new Result(Result.Status.ERROR, e.getMessage());
            }
            return new Result(Result.Status.ERROR, "还款失败");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/queryapply", method = RequestMethod.GET)
    public Result queryApply(HttpServletRequest request, Pageable page) {
        try {
            SessionUser uservo = CommonUtils.getSessionUser(request);
            int joinid = uservo.getId();
            List<TbSlProcessInfoVO> list =tbSlProcessInfoService.queryTbSlProcessInfoVo(page,joinid);
            return new Result(Result.Status.OK, list);
        } catch (Exception e) {
            LogUtils.error(log, e, "查询商户的申请记录报错");
            if (e instanceof BusinessException) {
                return new Result(Result.Status.ERROR, e.getMessage());
            }
            return new Result(Result.Status.ERROR, "查询商户的申请记录报错");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/cacelapply", method = RequestMethod.POST)
    public Result cancelApply(HttpServletRequest request, Integer processId) {
        try {
            loanService.updateForCancelCreditInfo(processId);
            return new Result(Result.Status.OK, "取消贷款申请书成功");
        } catch (Exception e) {
            LogUtils.error(log, e, "取消贷款的申请书失败");
            return new Result(Result.Status.ERROR, "取消贷款申请书失败");
        }

    }


    @ResponseBody
    @RequestMapping(value = "/queryStatTotal", method = RequestMethod.GET)
    public Result queryStatTotal(HttpServletRequest request, @RequestParam Integer id, Pageable page) {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        if (id == null) {
            return new Result(Result.Status.ERROR, "未选择任何平台");
        }
        try {
            List<TbSlLoanStatTotalVo> list = slLoanStatTotalService.queryByJoinidandPlatform(joinid, id, page);
            return new Result(Result.Status.OK, list);
        } catch (Exception e) {
            LogUtils.error(log, e, "查询平台的统计信息出错");
        }
        return new Result(Result.Status.ERROR, "查询平台的应收账款统计信息出错");

    }

    @ResponseBody
    @RequestMapping(value="/queryCredit",method = RequestMethod.GET)
    public Result queryCreditLog(HttpServletRequest request,Pageable page){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{
            List<TbSlLoanCreditLog> list= creditService.queryCreditByJoinid(joinid,page);
            return new Result(Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询用户的贷款数据出错");
        }
       return new Result(Status.ERROR,"查询用户的贷款数据出错");
    }

    /**
     * 查询商户的还款记录
     * @param request
     * @param page
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/queryRefund",method = RequestMethod.GET)
    public Result 阙queryRefund(HttpServletRequest request,Pageable page){

        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{
            List<TbSlLoanRefundVo> list= refundService.queryLoanRefundlist(joinid,page);
            return new Result(Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询用户的贷款数据出错");
        }
        return new Result(Status.ERROR,"查询用户的贷款数据出错");
    }

    @ResponseBody
    @RequestMapping(value="/queryRefundTotal",method = RequestMethod.GET)
    public Result queryRefundTotal(HttpServletRequest request,Pageable page){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{
            List<TbSlLoanInfoLog> list=tbSLLoanInfoLogService.queryTbSlLoanInfoLogByJoinid(joinid,page);
            return new Result(Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询用户的贷款统计数据出错");
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询用户的贷款统计数据出错");

        }
    }
    @ResponseBody
    @RequestMapping(value="/preLoan",method = RequestMethod.GET)
    public Result preLoan(HttpServletRequest request,String amount){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        String mthno = TradeUtils.getMhtNo(request);
        if(CommonUtils.isEmpty(amount)){
            return new Result(Status.ERROR,"请输入提款金额");
        }

        double amountdouble = Double.parseDouble(amount);
        if(amountdouble<10000){
            return new Result(Status.ERROR,"融资最小额度为10000元");
        }
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();

        try{
            TbSlLoanCreditVoForFront voForFront = loanService.queryPreLoan(amountlong,joinid,mthno,ISLConstDef.MERCHANT_TYPE);
            return new Result(Status.OK,voForFront);
        } catch (Exception e){
            LogUtils.error(log,e,"预提款失败");
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return  new Result(Status.ERROR,"系统异常");
        }

    }
    @ResponseBody
    @RequestMapping(value="/preRefund",method = RequestMethod.GET)
    public Result  preRefund(HttpServletRequest request,String amount){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        String mthno = TradeUtils.getMhtNo(request);
        if(CommonUtils.isEmpty(amount)){
            return new Result(Status.ERROR,"输入的金额为空");
        }
        double amountdouble = Double.parseDouble(amount);
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        long liabilitiesAmount= tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(liabilitiesAmount<amountlong){
            return new Result(Status.ERROR,"还款金额大于欠款额");
        }
        try{
            String accbance=accountBaseService.queryBalance(mthno,IConstDef.ACCTYPE_BASE);
            if(CommonUtils.getLong(accbance)<amountlong){
                return new Result(Status.ERROR,"账户余额不足,请先充值");
            }
            TbSlRefundForFrontVo vo =loanService.autoGenerationRefund(amountlong,joinid,mthno,"mch");
            return new Result(Status.OK,vo);
        }catch (Exception e){
            LogUtils.error(log,e,"xitong");
            if(e instanceof  BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"系统异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/autoRefund",method = RequestMethod.POST)
    public Result autoRefund(HttpServletRequest request,@RequestBody SlRapayParam param){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        String mthno = TradeUtils.getMhtNo(request);
        if(CommonUtils.isEmpty(param.getAmount())){
            return new Result(Status.ERROR,"请输入还款金额");
        }
        double amountdouble = Double.parseDouble(param.getAmount());
        BigDecimal decimal = new BigDecimal(amountdouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
        long amountlong = decimal.longValue();
        if(amountlong<=0){
            return new Result(Status.ERROR,"还款金额必须大于0元");
        }
        try{
            String accbance=accountBaseService.queryBalance(mthno,IConstDef.ACCTYPE_BASE);
            if(CommonUtils.getLong(accbance)<amountlong){
                return new Result(Status.ERROR,"账户余额不足,请先充值");
            }
            long liabilitiesAmount= tbSlLoanInfoService.queryTotalNotPayback(joinid);
            if(liabilitiesAmount<amountlong){
                return new Result(Status.ERROR,"还款金额大于欠款额");
            }
            String pwd=rsaSrv.decryptStringByJs(param.getPwd());
            loanService.updateForAutoRepayLoanByJoinid(amountlong, joinid, mthno,pwd,param.getVo());
            return new Result(Status.OK,"还款成功");
        }catch (Exception e){
            if(e instanceof IPayNowException){
                return new Result(Status.WARNING,"处理中");
            }
            if(e instanceof  BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"还款失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/querynotpaybackamount",method = RequestMethod.GET)
    public Result  querynotpayback(HttpServletRequest request){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{
           long amount= tbSlLoanInfoService.queryTotalNotPayback(joinid);
            return new Result(Status.OK,amount);
        }catch (Exception e){
            LogUtils.error(log,e,"查询商户的负债额报错");
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询商户的负债额报错");
        }


    }
    @ResponseBody
    @RequestMapping(value="/queryplatformdetail",method = RequestMethod.GET)
    public Result queryplatformdetail(HttpServletRequest request){
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{

            List<TbSlPlatformUserWithdrawVO> list=loanService.queryPlatformDetail(joinid);
            return new Result(Status.OK,list);
        }catch (Exception e){
           LogUtils.error(log,e,"查询平台明细有误");
            if(e instanceof  BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询平台明细有误");
        }
    }
    
    @ResponseBody
    @RequestMapping(value="/queryCardList",method = RequestMethod.GET)
	public Result queryCardList(HttpServletRequest request) {
		SessionUser uservo = CommonUtils.getSessionUser(request);
		int joinid = uservo.getId();
		List<TbSlBankacc> list = tbBankaccService.queryBankaccByJoinid(joinid);
		for(TbSlBankacc banckacc: list)
		if(null!=banckacc){
        	String displayBranchNo=branchBaseService.queryDisplayBranchNo(String.valueOf(banckacc.getUnionBankNo()));
        	banckacc.setDisplayBranchNo(displayBranchNo);
        }
		return new Result(Status.OK, list);
	}
    
    @ResponseBody
    @RequestMapping(value="/addCard",method = RequestMethod.POST)
	public Result addCard(HttpServletRequest request,TbSlBankacc bank) {
    	List<Pair> validBean=CommonUtils.beanValid(bank);
		if(CollectionUtils.isNotEmpty(validBean)){
    		return new Result(Result.Status.ERROR, validBean.get(0).second);
    	}
		
		SessionUser uservo = CommonUtils.getSessionUser(request);
		int joinid = uservo.getId();
		bank.setIdOfTbMerchantUser(joinid);
	    tbBankaccService.insert(bank);
        int id=bank.getId();
		return new Result(Status.OK, id);
	}
    @ResponseBody
    @RequestMapping(value="/querywillexpire",method = RequestMethod.GET)
    public Result queryWillExpire(HttpServletRequest request,Pageable page)
    {
        SessionUser uservo = CommonUtils.getSessionUser(request);
        int joinid = uservo.getId();
        try{

            List<TbSlLoanCreditLog> list=creditService.queryWillExpire(joinid,page);
            return new Result(Status.OK,list);
        }catch (Exception e){
            LogUtils.error(log,e,"查询即将到期融资款有误");
            if(e instanceof  BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询即将到期融资款有误");
        }

    }
    @ResponseBody
    @RequestMapping(value = "/applyRenewed",method = RequestMethod.POST)
    public Result  applyRenewed(HttpServletRequest request,Integer id,String rowUpdateTime,String renewedUpload){
        if(CommonUtils.isEmpty(id)){
            return new Result(Status.ERROR,"贷款记录不能为空");
        }
        if(CommonUtils.isEmpty(rowUpdateTime)){
            return new Result(Status.ERROR,"时间戳不能为空");
        }
        if(CommonUtils.isEmpty(renewedUpload)){
            return new Result(Status.ERROR,"展期申请书不能为空");
        }
        try{
           loanService.updateforapplyRenewed(id,rowUpdateTime,renewedUpload);
            return new Result(Status.OK,"展期申请成功");
            }catch (Exception e){
           LogUtils.error(log,e,"展期申请失败");
              if (e instanceof BusinessException){
                  return new Result(Status.ERROR,e.getMessage());
              }
                  return new Result(Status.ERROR,"展期申请失败");
        }


    }






    }

    

